import {
	tdt
} from "../common/config.js"

/**
 * 将服务添加至地图上
 * @param {Array} 	layers		服务图层
 * @param {Number} 	wkid		空间参考
 * @param {Number} 	res			返回layers, 与return返回结果一致
 * @param {Object} 	Arcgis		Arcgis方法类
 * @returns []	处理后的layers, 可通过viewer.map.addMany(layers) 添加到地图
 */
export const getMapLayers = ({
	layers = [],
	wkid = 4490,
	res = [],
	Arcgis: {
		SpatialReference,
		TileInfo,
		WebTileLayer,
		MapImageLayer,
		TileLayer,
		FeatureLayer,
	}
}) => {
	if (!layers || !Array.isArray(layers)) return res

	//  空间参考
	let spatialReference = new SpatialReference({
		wkid: wkid ? wkid : 4490
	});

	const objMethod = {
		// 天地图
		tianditu: (data) => {
			let {
				TDTBaseUrl,
				TdtToken,
				subDomains,
				tdtTileInfo
			} = tdt;
			let {
				service = 'WMTS', layerType = 'img', version = '1.0.0',
					request = 'GetTile',
					tileMatrixSet =
					'w', style = 'default', format = 'tiles', title = "_title",
					visible =
					true,
					opacity = 1,
					id
			} = data;
			//  配置模板url
			let urlTemplate =
				`${tdt.TDTBaseUrl}/${layerType}_${tileMatrixSet}/${service.toLowerCase()}?SERVICE=${service}&REQUEST=${request}&VERSION=${version}&LAYER=${layerType}&STYLE=${style}&TILEMATRIXSET=${tileMatrixSet}&FORMAT=${format}&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=${tdt.TdtToken}`;
			//  设置天地图切片配置的空间参考
			let bufferTdtTileInfo = JSON.parse(JSON.stringify(tdt.tdtTileInfo));
			bufferTdtTileInfo.spatialReference = spatialReference

			let layerConfig = {
				urlTemplate,
				subDomains: tdt.subDomains,
				title,
				visible,
				opacity,
				spatialReference,
				id
			};
			if (wkid == 4490) {
				layerConfig.tileInfo = new TileInfo(bufferTdtTileInfo)
			}
			return new WebTileLayer(layerConfig);
		},
		// 动态服务图层
		dynamic: (data) => {
			let params = {
				...data,
				spatialReference,
			}
			return new MapImageLayer(params);
		},
		// 切片服务
		tile: (data) => {
			let params = {
				...data,
				spatialReference,
			}
			return new TileLayer(params);
		},
		// feature 服务
		feature: (data) => {
			let params = {
				...data,
				spatialReference,
			}
			return new FeatureLayer(params);
		},
	}

	res = layers.filter(item => objMethod[item.serviceType]).map(item => {
		return objMethod[item.serviceType](item)
	})
	return res
}